package in.co.codedoc.cg.velocity;

import in.co.codedoc.cg.CGAnnotationProcessor;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.parser.node.Node;

import com.sun.mirror.apt.Filer;

public class CreateTextFileDirective extends CGBlockDirective
{
	public CreateTextFileDirective()
	{
		super("the package in which the generated file must lie in","the name of the text file");
	}

	@Override
	public String getName()
	{
		return "CreateTextFile";
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer,
			Node node) throws IOException, ResourceNotFoundException,
			ParseErrorException, MethodInvocationException
	{
		String filePackage = getArgument(context, node, 0);
		String fileName = getArgument(context, node, 1);

		PrintWriter fw 
			= CGAnnotationProcessor.getProcessor().getEnv()
				.getFiler().createTextFile(Filer.Location.CLASS_TREE, filePackage, new File(fileName), null);

		try
		{
			node.jjtGetChild(2).render(context,fw);
		}
		finally
		{
			if(fw != null)
			{
				fw.flush();
				fw.close();
			}
		}
		
		return true;
	}
}
